package com.atguigu.product.entity.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * description: GulimallExceptionControllerAdvice
 * date: 2022/10/18 10:41
 * author: MR.孙
 */
@Slf4j
@RestControllerAdvice
public class GulimallExceptionControllerAdvice {


    /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidExcpetion(MethodArgumentNotValidException e){

        log.error("数据校验出现问题{}, 异常类型为:{}", e.getMessage(), e.getClass());

        HashMap<String, String> errorMap = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach((item)->{

            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();

            errorMap.put(field, defaultMessage);

        });

        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMessage())
                .put("data", errorMap);
    }


    /**
     *
     * 处理全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(value=Throwable.class)
    public R handleException(Throwable e){

        log.error("异常消息{}, 异常类型为:{}", e.getMessage(), e.getClass());
        log.error("错误：", e);
        return R.error(BizCodeEnume.UNKNOW_EXEPTION.getCode(), BizCodeEnume.UNKNOW_EXEPTION.getMessage());


    }
}
